<template>
    <div class="menu-container auto-height-container">
        <vab-query-form>
            <vab-query-form-left-panel :span="24">
                <el-button v-permissions="{
                    permission: ['system:menu:doAdd']
                }" type="primary" @click="handleAdd()" :icon="Plus">新增</el-button>
            </vab-query-form-left-panel>
        </vab-query-form>

        <!-- 树形表格 -->
        <el-table :data="menuList" row-key="menu_id" border default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" height="100%">
            <el-table-column prop="title" label="菜单名称" min-width="140" align="center" show-overflow-tooltip />
            <el-table-column prop="name" label="路由名称" min-width="100" align="center" show-overflow-tooltip />
            <el-table-column prop="path" label="路由路径" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="component" label="组件路径" min-width="240" align="center" show-overflow-tooltip />
            <el-table-column prop="icon" label="图标" width="70" align="center">
                <template #default="{ row }">
                    <vab-icon v-if="row.icon" :icon="row.icon" :is-custom-svg="row.is_custom_svg === 1" />
                </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="100" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    <el-tag :type="row.type === 1 ? 'primary' : 'success'">
                        {{ row.type === 1 ? '菜单' : '页面/按钮' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="perms" label="权限标识" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="sort" label="排序" width="80" align="center" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="80" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                        {{ row.status === 1 ? '正常' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="240" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button v-permissions="{
                        permission: ['system:menu:doEdit']
                    }" type="primary" link @click="handleEdit(row)">编辑</el-button>
                    <el-button v-permissions="{
                        permission: ['system:menu:doAdd']
                    }" type="primary" link @click="handleAdd(row)">添加子菜单</el-button>
                    <el-button v-permissions="{
                        permission: ['system:menu:doDelete']
                    }" type="danger" link @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 菜单表单组件 -->
        <menu-form-edit v-model:visible="dialogVisible" :type="dialogType" :menu-options="menuOptions"
            :current-row="currentRow" @success="handleSuccess" />
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, User } from '@element-plus/icons-vue'
import { getMenuList, deleteMenu, createMenu } from '/@/api/menu'
import type { MenuForm } from '/@/api/menu'
import MenuFormEdit from './components/MenuForm.vue'

const menuList = ref([])
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentRow = ref<MenuForm | null>(null)

// 获取菜单列表
const fetchMenuList = async () => {
    try {
        const { data } = await getMenuList()
        menuList.value = data
    } catch (error) {
        console.error('获取菜单列表失败:', error)
    }
}

// 处理搜索
const handleSearch = () => {
    fetchMenuList()
}

// 处理新增
const handleAdd = (row?: any) => {
    dialogType.value = 'add'
    currentRow.value = row || null
    dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: MenuForm) => {
    dialogType.value = 'edit'
    currentRow.value = row
    dialogVisible.value = true
}

// 修改删除处理方法
const handleDelete = async (row: MenuForm) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该菜单吗？删除后将无法恢复！',
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        await deleteMenu(row.menu_id!)
        ElMessage.success('删除成功')
        fetchMenuList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
        }
    }
}

// 处理表单提交成功
const handleSuccess = () => {
    fetchMenuList()
}

// 计算菜单选项
const menuOptions = computed(() => {
    const options = [{
        menu_id: 0,
        title: '顶级菜单',
        children: []
    }]

    // 过滤掉当前编辑的菜单及其子菜单，防止自己选择自己作为父级
    const filterMenus = (menus: any[], currentId?: number): any[] => {
        if (!currentId) return menus
        return menus.filter(menu => {
            if (menu.menu_id === currentId) return false
            if (menu.children) {
                menu.children = filterMenus(menu.children, currentId)
            }
            return true
        })
    }

    // 当处于编辑状态时，需要过滤掉当前菜单及其子菜单
    const filteredMenus = filterMenus(
        JSON.parse(JSON.stringify(menuList.value)),
        dialogType.value === 'edit' ? currentRow.value?.menu_id : undefined
    )

    return options.concat(filteredMenus)
})

onMounted(() => {
    fetchMenuList()
})
</script>

<style lang="scss" scoped></style>